<!doctype html>



  


<html class="theme-next mist use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>



<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />















  
  
  <link href="/blog/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />




  
  
  
  

  
    
    
  

  

  

  

  

  
    
    
    <link href="//fonts.googleapis.com/css?family=Lato:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






<link href="/blog/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/blog/css/main.css?v=5.1.0" rel="stylesheet" type="text/css" />


  <meta name="keywords" content="java,jvm," />








  <link rel="shortcut icon" type="image/x-icon" href="/blog/favicon.ico?v=5.1.0" />






<meta name="description" content="什么是对象逃逸Java中对象逃逸指的是：在方法中创建的对象，我们知道这个对象引用在栈中，被当前线程独享。如果该对象引用可被其他线程拥有，则说该对象发生逃逸。  局部变量逃逸  方法值返回逃逸  对像引用逃逸 /** * 对象逃逸 * Created by Niki on 2018/5/10 14:04 */public class ObjectEscape &amp;#123;    private Ob">
<meta name="keywords" content="java,jvm">
<meta property="og:type" content="article">
<meta property="og:title" content="JVM-TLAB之逃逸分析">
<meta property="og:url" content="https://gitee.com/shuhao/2018/05/09/JVM-TLAB之逃逸分析/index.html">
<meta property="og:site_name" content="Niki">
<meta property="og:description" content="什么是对象逃逸Java中对象逃逸指的是：在方法中创建的对象，我们知道这个对象引用在栈中，被当前线程独享。如果该对象引用可被其他线程拥有，则说该对象发生逃逸。  局部变量逃逸  方法值返回逃逸  对像引用逃逸 /** * 对象逃逸 * Created by Niki on 2018/5/10 14:04 */public class ObjectEscape &amp;#123;    private Ob">
<meta property="og:locale" content="zh-Hans">
<meta property="og:image" content="https://gitee.com/blog/images/java/jvm/tlab_error_1.jpg">
<meta property="og:updated_time" content="2018-05-28T01:56:48.016Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="JVM-TLAB之逃逸分析">
<meta name="twitter:description" content="什么是对象逃逸Java中对象逃逸指的是：在方法中创建的对象，我们知道这个对象引用在栈中，被当前线程独享。如果该对象引用可被其他线程拥有，则说该对象发生逃逸。  局部变量逃逸  方法值返回逃逸  对像引用逃逸 /** * 对象逃逸 * Created by Niki on 2018/5/10 14:04 */public class ObjectEscape &amp;#123;    private Ob">
<meta name="twitter:image" content="https://gitee.com/blog/images/java/jvm/tlab_error_1.jpg">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/blog/',
    scheme: 'Mist',
    sidebar: {"position":"right","display":"post","offset":12,"offset_float":0,"b2t":false,"scrollpercent":false},
    fancybox: true,
    motion: true,
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://gitee.com/shuhao/2018/05/09/JVM-TLAB之逃逸分析/"/>





  <title> JVM-TLAB之逃逸分析 | Niki </title>
</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  





  <script type="text/javascript">
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?cb9f0585e406f878cb2f29c89ad3cdb7";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>










  
  
    
  

  <div class="container one-collumn sidebar-position-right page-post-detail ">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/blog/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Niki</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">天道酬勤</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/blog/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/blog/categories" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-categories"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/blog/archives" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/blog/tags" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal " itemscope itemtype="http://schema.org/Article">
    <link itemprop="mainEntityOfPage" href="https://gitee.com/shuhao/blog/2018/05/09/JVM-TLAB之逃逸分析/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="Fang ShuHao">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/blog/images/head.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Niki">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">
            
            
              
                JVM-TLAB之逃逸分析
              
            
          </h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2018-05-09T19:59:58+08:00">
                2018-05-09
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/blog/categories/java/" itemprop="url" rel="index">
                    <span itemprop="name">java</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          

          

          

        </div>
      </header>
    


    <div class="post-body" itemprop="articleBody">

      
      

      
        <h2 id="什么是对象逃逸"><a href="#什么是对象逃逸" class="headerlink" title="什么是对象逃逸"></a>什么是对象逃逸</h2><p>Java中对象逃逸指的是：在方法中创建的对象，我们知道这个对象引用在栈中，被当前线程独享。如果该对象引用可被其他线程拥有，则说该对象发生逃逸。</p>
<ol>
<li><p>局部变量逃逸</p>
</li>
<li><p>方法值返回逃逸</p>
</li>
<li><p>对像引用逃逸</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 对象逃逸</span></span><br><span class="line"><span class="comment"> * Created by Niki on 2018/5/10 14:04</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">ObjectEscape</span> </span>&#123;</span><br><span class="line">    <span class="keyword">private</span> Object a ;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">test1</span><span class="params">()</span></span>&#123;</span><br><span class="line">        <span class="comment">//局部变量逃逸</span></span><br><span class="line">        a = <span class="keyword">new</span> Object();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> Object <span class="title">test2</span><span class="params">()</span></span>&#123;</span><br><span class="line">        Object obj = <span class="keyword">new</span> Object();</span><br><span class="line">        <span class="comment">//对象返回逃逸</span></span><br><span class="line">        <span class="keyword">return</span> obj ;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">test3</span><span class="params">()</span></span>&#123;</span><br><span class="line">        <span class="comment">//实例对象引用发生逃逸</span></span><br><span class="line">        Object ojb = test2();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
</li>
</ol>
<h2 id="对象逃逸优化JVM原理"><a href="#对象逃逸优化JVM原理" class="headerlink" title="对象逃逸优化JVM原理"></a>对象逃逸优化JVM原理</h2><p>我们先来回顾一下Java堆和Java栈相关的知识：</p>
<ol>
<li>Java的对象都是在Java堆上创建的，堆上的对象被所有线程共享是线程不安全的。</li>
<li>方法中的局部变量都是在栈中分配内存空间，有线程独有，不存在线程安全问题。</li>
<li>堆上的对象创建后，如果不使用，经过JVM对象可达性分析后，确认是否可以GC回收。GC回收会给系统带来压力，间接影响系统的性能。</li>
</ol>
<p>好了，那么再方法体内的对象是怎么创建的呢？<br>方法体中的对象在堆中分配内存，并且在调用的栈中保存了对象的指针。</p>
<p>那么我们怎么减少GC提升性能呢？，不创建对象（what？那你玩啥呢？）<br>既然不能不创建对象，我们是不是可以将对象分配空间换个位置——比如栈空间！！。栈空间的内存随着线程的结束会被JVM自动回收，因为栈中的数据都是线程安全的，那么再分配对对象的时候也无需锁定，减少阻塞的开销。正因为是线程安全的，栈上的对象分配会去掉同步锁运行。</p>
<p>好了，就可以利用对象逃逸分析来进行这样的操作。</p>
<h3 id="开启对象逃逸分析"><a href="#开启对象逃逸分析" class="headerlink" title="开启对象逃逸分析"></a>开启对象逃逸分析</h3><figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">-server -verbose:gc -XX:+DoEscapeAnalysis</span><br></pre></td></tr></table></figure>
<p>开启对象逃逸分析后，如果对象未发生逃逸，则JVM将变量类的实例化内存直接在栈中分配，无需进入堆。在调用栈内执行，最后线程结束，栈空间被回收，则局部变量的对象也被回收。</p>
<h3 id="注意"><a href="#注意" class="headerlink" title="注意"></a>注意</h3><p>逃逸分析不能在静态编译时进行，必须在JIT里完成。原因是，与java的动态性有冲突。因为你可以在运行时，通过动态代理改变一个类的行为，此时，逃逸分析是无法得知类已经变化了。</p>
<h2 id="TLAB内存问题"><a href="#TLAB内存问题" class="headerlink" title="TLAB内存问题"></a>TLAB内存问题</h2><p>TLAB能很好的解决分配内存时的性能问题。（每个线程在堆上自有一块空间，分配时无需加锁）但是在对象回收时可能会产生附加的内存问题。具体是什么呢？</p>
<ol>
<li>为什么在程序运行时，在线程中创建一个很小的对象，查看JProfiler可以看到很多无用的int数组对象。<br>JVM在GC或者内存dump，都必须对内存做一个遍历，因此必须先暂停java线程，防止在遍历内存里的对象的时候，进行内存分配；但是每个线程分配内存都是优先走TLAb，为了能快速遍历对象，而不存在不连续的内存，于是JVM会对TLAB做一个填充，填充的正好是int数组对象，将剩下的没被分配的TLAB内存给填满，因此在系统运行过程中，可能伴随很多无用的对象产生。</li>
</ol>
<p>异常demo<br><img src="/blog/images/java/jvm/tlab_error_1.jpg"></p>
<blockquote>
<blockquote>
<p>参考<br><a href="https://blog.csdn.net/kinger0/article/details/47357333" target="_blank" rel="external">逃逸分析</a><br><a href="http://www.10tiao.com/html/677/201712/2650887123/1.html" target="_blank" rel="external">不起眼，但是足以让你收获的JVM内存案例</a></p>
</blockquote>
</blockquote>

      
    </div>

    <div>
      
        

      
    </div>

    <div>
      
        

      
    </div>


    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/blog/tags/java/" rel="tag"># java</a>
          
            <a href="/blog/tags/jvm/" rel="tag"># jvm</a>
          
        </div>
      

      
        
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/blog/2018/05/09/JavaNIO之三：通道Channel/" rel="next" title="JavaNIO之三：通道Channel">
                <i class="fa fa-chevron-left"></i> JavaNIO之三：通道Channel
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/blog/2018/05/10/redis底层数据结构/" rel="prev" title="redis底层数据结构">
                redis底层数据结构 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </article>



    <div class="post-spread">
      
    </div>
  </div>

          
          </div>
          


          
  <div class="comments" id="comments">
    
      <div id="lv-container" data-id="city" data-uid="MTAyMC8zNjY5NS8xMzIzMA=="></div>
    
  </div>


        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap" >
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
          <img class="site-author-image" itemprop="image"
               src="/blog/images/head.jpg"
               alt="Fang ShuHao" />
          <p class="site-author-name" itemprop="name">Fang ShuHao</p>
           
              <p class="site-description motion-element" itemprop="description"></p>
          
        </div>
        <nav class="site-state motion-element">
        
          
            <div class="site-state-item site-state-posts">
              <a href="/blog/archives">
                <span class="site-state-item-count">135</span>
                <span class="site-state-item-name">日志</span>
              </a>
            </div>
          

          
            <div class="site-state-item site-state-categories">
              <a href="/blog/categories">
                <span class="site-state-item-count">35</span>
                <span class="site-state-item-name">分类</span>
              </a>
            </div>
          

          
            <div class="site-state-item site-state-tags">
              <a href="/blog/tags">
                <span class="site-state-item-count">93</span>
                <span class="site-state-item-name">标签</span>
              </a>
            </div>
          

        </nav>

        

        <div class="links-of-author motion-element">
          
        </div>

        
        

        
        

        


      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#什么是对象逃逸"><span class="nav-number">1.</span> <span class="nav-text">什么是对象逃逸</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#对象逃逸优化JVM原理"><span class="nav-number">2.</span> <span class="nav-text">对象逃逸优化JVM原理</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#开启对象逃逸分析"><span class="nav-number">2.1.</span> <span class="nav-text">开启对象逃逸分析</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#注意"><span class="nav-number">2.2.</span> <span class="nav-text">注意</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#TLAB内存问题"><span class="nav-number">3.</span> <span class="nav-text">TLAB内存问题</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright" >
  
  &copy; 
  <span itemprop="copyrightYear">2019</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Fang ShuHao</span>
</div>


<div class="powered-by">
  由 <a class="theme-link" href="https://hexo.io">Hexo</a> 强力驱动
</div>

<div class="theme-info">
  主题 -
  <a class="theme-link" href="https://github.com/iissnan/hexo-theme-next">
    NexT.Mist
  </a>
</div>


        

        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    
    
  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  




  
  <script type="text/javascript" src="/blog/lib/jquery/index.js?v=2.1.3"></script>

  
  <script type="text/javascript" src="/blog/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>

  
  <script type="text/javascript" src="/blog/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>

  
  <script type="text/javascript" src="/blog/lib/velocity/velocity.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/blog/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/blog/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>


  


  <script type="text/javascript" src="/blog/js/src/utils.js?v=5.1.0"></script>

  <script type="text/javascript" src="/blog/js/src/motion.js?v=5.1.0"></script>



  
  

  
  <script type="text/javascript" src="/blog/js/src/scrollspy.js?v=5.1.0"></script>
<script type="text/javascript" src="/blog/js/src/post-details.js?v=5.1.0"></script>



  


  <script type="text/javascript" src="/blog/js/src/bootstrap.js?v=5.1.0"></script>



  



  




	





  





  





  
    <script type="text/javascript">
      (function(d, s) {
        var j, e = d.getElementsByTagName(s)[0];
        if (typeof LivereTower === 'function') { return; }
        j = d.createElement(s);
        j.src = 'https://cdn-city.livere.com/js/embed.dist.js';
        j.async = true;
        e.parentNode.insertBefore(j, e);
      })(document, 'script');
    </script>
  



  
  

  

  

  

  


  

</body>
</html>
